<template>
  <div class="devices flex-column h-100P">
    <QueryContainer style="padding:0 0 20px 0;" @reset="handleReset" @search="handleSearch">
      <el-form :model="queryInfo" inline label-width="70px" ref="form" label-position="left">
        <el-form-item label="关键词" prop="keyword">
          <el-input
            class="input"
            v-model="queryInfo.keyword"
            placeholder="请输入设备编号或设备名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </QueryContainer>
    <div class="flex">
      <CustomButton @click="handleAddDevice" title="添加设备"></CustomButton>
      <div class="multiple-control" v-if="selectedDevicesList.length">
        <el-button type="text" class="link-text fz-14" @click="handleMultiChangeTaskStatus">
          批量变更任务状态
        </el-button>
        <el-button type="text" class="link-text fz-14" @click="handleMultiDel()">
          批量删除
        </el-button>
        <el-button type="text" class="link-text fz-14" @click="handleCancelSelect">取消</el-button>
      </div>
    </div>
    <div class="flex-sub mg-top-20" style="max-height: 50vh;">
      <el-table
        :data="tableData"
        v-loading="loading"
        height="98%"
        header-cell-class-name="table-header-cell"
        header-row-class-name="table-header-row"
        @selection-change="handleSelectionChange"
        row-key="id"
        ref="table"
      >
        <el-table-column :reserve-selection="true" type="selection" width="45"></el-table-column>
        <el-table-column prop="deviceVo.name" label="设备编号"></el-table-column>
        <el-table-column prop="deviceVo.remarkName" label="设备名称"></el-table-column>
        <!--        <el-table-column prop="productName" label="所属产品"></el-table-column>-->
        <!--        <el-table-column prop="netTypeEnum" label="入网类型"></el-table-column>-->
        <el-table-column prop="online" label="在线状态">
          <template v-slot="{row}">
            <div class="offline" :class="{online: row.deviceVo.online}">
              {{ row.deviceVo.online ? '在线' : '离线' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="activeTime" label="最近在线时间">
          <template v-slot="{row}">
            {{ row.activeTime|dateTimeFormatter }}
          </template>
        </el-table-column>
        <el-table-column label="算法任务开/关">
          <template slot-scope="{row}">
            <div class="align-center">
              <el-switch
                v-model="row.working"
                :disabled="!row.deviceVo.online"
                active-color="#67C23A"
                @change="handleChangeTaskStatus(row)"
              />
              <span class="mg-left-10">{{ row.dataStatusName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="{row}">
            <div class="control">
              <el-button type="text" size="mini" class="link-text fz-14" @click="handleCheck(row)">
                查看
              </el-button>
              <el-button type="text" size="mini" class="primary-text fz-14" @click="handleDel(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <img :src="emptyImage" alt="" />
        </template>
      </el-table>
    </div>
    <el-pagination
      hide-on-single-page
      background
      layout="prev, pager, next, total, jumper"
      :total="queryInfo.total"
      :page-size="queryInfo.pageSize"
      @current-change="handlePageNoChange"
    />
    <DeviceSelector
      :visible.sync="dialogVisible"
      :config="{title:'绑定设备至算法能力',confirmButtonText:'添加',cancelButtonText:'取消',excludeBusinessTypeEnum:'ALG'}"
      @confirm="handleAddDeviceIntoGroup"
    />
  </div>
</template>

<script>
import {
  apiAddAbilityBatch,
  apiDelAbilityDeviceBatch,
  apiFindDevicePageByParam,
  apiStartTask,
  apiStopTask,
} from '@/views/algorithm/alg-task/api'
import QueryContainer from '@/components/query-container/index'
// import SelectNetType from '@/views/device/deploy-device/components/select-net-type'
// import SelectDeviceOnlineState from '@/views/device/deploy-device/components/select-device-online-state'
// import SelectProduct from '@/views/device/create-product/components/select-product'
import CustomButton from '@/components/custom-button'
import DeviceSelector from '@/components/device-selector'

export default {
  name: 'Devices',
  props: {
    ability: {
      type: Object,
      require: true,
      default: () => ({}),
    },
  },
  components: {
    QueryContainer,
    // SelectNetType,
    // SelectDeviceOnlineState,
    // SelectProduct,
    CustomButton,
    DeviceSelector,
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      queryInfo: {
        netType: '',
        taskId: '',
        keyword: '',
        onlineState: '',
        productId: '',
        total: 0,
        pageSize: 14,
        pageNo: 1,
      },
      tableData: [],
      selectedDevicesList: [],
    }
  },
  created() {
    this.initPage()
  },
  computed: {
    emptyImage() {
      return `${this.$consts.OSS_STATIC_IMAGE_URL}/empty.png`
    },
  },
  methods: {
    initPage() {
      this.queryInfo.abilityId = this.$route.query.abilityId
      this.handleSearch()
    },
    handlePageNoChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.handleSearch()
    },
    handleAddDevice() {
      if (this.ability.dataStatusEnum === 'WORKING') {
        this.$confirm(
          '处于运行中状态的算法任务无法添加设备请更改为关闭状态后重试。',
          '无法添加设备',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
          }
        )
      } else {
        this.dialogVisible = true
      }
    },
    handleSelectionChange(val) {
      this.selectedDevicesList = val
    },
    handleReset() {
      this.$refs.form.resetFields()
      this.handleSearch()
    },
    handleCheck(device) {
      this.$router.push({
        path: '/device/deploy-device-detail',
        query: { deviceId: device.deviceVo.id },
      })
    },
    handleAddDeviceIntoGroup(deviceList) {
      const abilityId = this.$route.query.abilityId
      apiAddAbilityBatch(
        deviceList.map(({ id }) => ({
          deviceId: id,
          abilityId: abilityId,
        }))
      ).then(() => {
        this.$message.success('设备添加成功')
        this.handleSearch()
      })
    },
    handleDel(device) {
      this.handleMultiDel([device.id])
    },
    handleSearch() {
      this.findDevice()
    },
    /**
     * 改变设备的任务状态
     */
    handleChangeTaskStatus({ id: id, working }) {
      const handleSuccess = () => {
        this.$message.success('状态切换成功')
        // this.handleSearch()
      }

      if (working) {
        apiStartTask(id).then(() => handleSuccess())
      } else {
        apiStopTask(id).then(() => handleSuccess())
      }
    },
    /**
     * 批量改变设备的任务状态
     */
    handleMultiChangeTaskStatus() {},

    /**
     * 批量删除设备
     */
    handleMultiDel(devicesIdList = this.selectedDevicesList.map(({ id }) => id)) {
      this.$confirm(
        '确定要将该设备从任务中移除吗？（请确保您的算法任务处于关闭状态）',
        '从任务中移除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        apiDelAbilityDeviceBatch(devicesIdList).then(() => {
          this.$message.success('删除设备成功')
          this.selectedDevicesList = []
          this.handleCancelSelect()
          this.handleSearch()
        })
      })
    },
    /**
     * 取消选择
     */
    handleCancelSelect() {
      this.$refs.table.clearSelection()
    },
    async findDevice() {
      this.loading = true
      const { total, pageSize, pageNo, records } = await apiFindDevicePageByParam(this.queryInfo)
      this.tableData = records
      this.queryInfo.pageSize = pageSize
      this.queryInfo.pageNo = pageNo
      this.queryInfo.total = total
      this.loading = false
    },
  },
}
</script>

<style scoped lang="scss">
.devices {
  .input {
    width: vw(350px);
  }

  .control {
    ::v-deep {
      .el-button + .el-button {
        position: relative;
        margin-left: 0;

        &::before {
          position: absolute;
          top: 55%;
          left: 0;
          display: block;
          width: 1px;
          height: 50%;
          background-color: #999;
          content: '';
          transform: translateY(-50%);
        }
      }
    }
  }
}

.offline {
  color: #d12d1f;
}

.online {
  color: rgb(103, 194, 58);
}
</style>
